package com.ys.utils.base.j2se;

import com.ys.utils.base.http.ResultUtil;
import okhttp3.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

public class HttpUtils {


	//实例化Http请求
	static OkHttpClient client = new OkHttpClient();

	//定义JSON提交头
	public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
	//上传文件
	public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");

	//GET方式请求
	public static String GET(String url) throws IOException {
		Request request = new Request.Builder().url(url).build();
		Response response = client.newCall(request).execute();
		return response.body().string();
	}

	//POST提交JSON
	public static String POST2JSON(String url, String json) throws IOException {
		RequestBody body = RequestBody.create(JSON, json);
		Request request = new Request.Builder().url(url).post(body).build();
		Response response = client.newCall(request).execute();
		return response.body().string();
	}

	public static String post(String url,Map<String,String> param){
		FormBody.Builder formBody = new FormBody.Builder();

		param.forEach(formBody::add);

		Request request = new Request.Builder()
				.url(url)
				.post(formBody.build())
				.build();
		try{
			Response response = client.newCall(request).execute();
			if (response.isSuccessful()) {
				return response.body().string();
			} else {
				throw new IOException("post Unexpected code " + response);
			}
		}catch (Exception e){
			throw new RuntimeException(e);
		}
	}

	//上传文件
    private static final String IMGUR_CLIENT_ID = "9199fdef135c122";
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("audio/mp4");
	public static void run() throws Exception {
		File file = new File("D://xxx.mp4");

        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("agentid", "1")
                .addFormDataPart("type", "video")
                .addFormDataPart("access_token", "Nt7vW11o90ExxbOC3wbg3tXXl-dXt672LK0bBeADfKtDAlLtpr073emyC9cCPD7eupV5RbkiL853aOEhiyeMGA")
                .addFormDataPart("media", "xxx.mp4",RequestBody.create(MEDIA_TYPE_PNG, file))
                .build();

        Request request = new Request.Builder()
                .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
                .url("https://qyapi.weixin.qq.com/cgi-bin/material/add_material")
                .post(requestBody)
                .build();

        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

        System.out.println(response.body().string());
	}

	// Main
	public static void main(String[] args) throws Exception {

	}

	public static String client(String url){
		return clientParam(null,url);
	}

	public static String clientParam(Map<String,Object> paramMap, String url){
		String result = "";
		try {
			//遍历参数
			FormBody.Builder newFormBody = new FormBody.Builder();
			if(null!=paramMap) {
				for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
					newFormBody.add(entry.getKey(), entry.getValue() + "");
				}
			}
			RequestBody formBody = newFormBody.build();
			Request request = new Request.Builder().header("content-type","application/json;charset=utf-8").url(url).post(formBody).build();
			Response response = client.newCall(request).execute();
			if (response.isSuccessful()) {
				result = response.body().string();
				response.close();
				return result;
			} else {
				response.close();
				throw new IOException("Unexpected code " + response);
			}
		}catch (Exception e ){
			e.printStackTrace();
		}
		return result;
	}


	/**
	 * post请求，参数为json字符串
	 * @param url 请求地址
	 * @param paramMap
	 * @return 响应
	 */
	public static String postJson(String url,Map<String,Object> paramMap)
	{

		String jsonString = JsonUtil.toJson(paramMap);
		String result = null;
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost post = new HttpPost(url);
		post.setHeader("Content-type", "application/json; charset=utf-8");
		CloseableHttpResponse response = null;
		try {
			post.setEntity(new ByteArrayEntity(jsonString.getBytes("UTF-8")));
			response = httpClient.execute(post);
			if(response != null && response.getStatusLine().getStatusCode() == 200)
			{
				HttpEntity entity = response.getEntity();
				result = entityToString(entity);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				httpClient.close();
				if(response != null)
				{
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.err.println(result);
		return result;
	}
	/**
	 * post请求，参数为json字符串
	 * @param url 请求地址
	 * @param paramMap
	 * @return 响应
	 */
	public static String postUrlEncodeJson(String url,Map<String,Object> paramMap)
	{

		String jsonString = JsonUtil.toJson(paramMap);
		jsonString = URLDecoder.decode(jsonString);
		String result = null;
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost post = new HttpPost(url);
		post.setHeader("Content-type", "application/json; charset=utf-8");
		CloseableHttpResponse response = null;
		try {
			post.setEntity(new ByteArrayEntity(jsonString.getBytes("UTF-8")));
			response = httpClient.execute(post);
			if(response != null && response.getStatusLine().getStatusCode() == 200)
			{
				HttpEntity entity = response.getEntity();
				result = entityToString(entity);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				httpClient.close();
				if(response != null)
				{
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.err.println(result);
		return result;
	}
	private static String entityToString(HttpEntity entity) throws IOException {
		String result = null;
		if(entity != null)
		{
			long lenth = entity.getContentLength();
			if(lenth != -1 && lenth < 2048)
			{
				result = EntityUtils.toString(entity,"UTF-8");
			}else {
				InputStreamReader reader1 = new InputStreamReader(entity.getContent(), "UTF-8");
				CharArrayBuffer buffer = new CharArrayBuffer(2048);
				char[] tmp = new char[1024];
				int l;
				while((l = reader1.read(tmp)) != -1) {
					buffer.append(tmp, 0, l);
				}
				result = buffer.toString();
			}
		}
		return result;
	}

	public static String clientParam1(Map<String,Object> paramMap, String url){
		String result = "";
		try {
			//遍历参数
			FormBody.Builder newFormBody = new FormBody.Builder();
			if(null!=paramMap) {
				for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
					newFormBody.add(entry.getKey(), URLEncoder.encode(entry.getValue() + ""));
				}
			}
			RequestBody formBody = newFormBody.build();
			Request request = new Request.Builder().header("content-type","application/json;charset=utf-8").url(url).post(formBody).build();
			Response response = client.newCall(request).execute();
			if (response.isSuccessful()) {
				result = response.body().string();
				response.close();
				return result;
			} else {
				response.close();
				throw new IOException("Unexpected code " + response);
			}
		}catch (Exception e ){
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * @param url    请求地址
	 * @param params 请求参数
	 * @return String
	 * @throws
	 * @Title: sendGet
	 * @Description: TODO(发送get请求)
	 * @author wangxy
	 * @date 2018年5月14日 下午2:32:39
	 */
	public static String sendGet(String url, Map<String, Object> params) {
		return sendGet(url, params, "utf-8");
	}

	/**
	 * @param url      请求地址
	 * @param params   请求参数
	 * @param encoding 编码
	 * @return String
	 * @throws
	 * @Title: sendGet
	 * @Description: TODO(发送get请求)
	 * @author wangxy
	 * @date 2018年5月14日 下午2:39:01
	 */
	public static String sendGet(String url, Map<String, Object> params, String encoding) {
		// 创建client
		CloseableHttpClient client = HttpClients.createDefault();
		// 创建HttpGet
		HttpGet httpGet = new HttpGet();
		try {
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
			// 封装参数
			if (params != null) {
				for (String key : params.keySet()) {
					builder.addParameter(key, params.get(key).toString());
				}
			}
			URI uri = builder.build();
			// 设置请求地址
			httpGet.setURI(uri);
			// 发送请求，返回响应对象
			CloseableHttpResponse response = client.execute(httpGet);
			return parseData(response);
		} catch (Exception e) {
			Logger.error("发送get请求失败", e);
		} finally {
			httpGet.releaseConnection();
		}
		return null;
	}
	/**
	 * @param url 请求地址
	 * @return String
	 * @throws
	 * @Title: sendGet
	 * @Description: TODO(发送get请求)
	 * @author wangxy
	 * @date 2018年5月14日 下午2:33:45
	 */
	public static String sendGet(String url) {
		return sendGet(url, null, "utf-8");
	}

	/**
	 * 解析response
	 *
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public static String parseData(CloseableHttpResponse response) throws Exception {
		// 获取响应状态
		int status = response.getStatusLine().getStatusCode();
		if (status == HttpStatus.SC_OK) {
			// 获取响应数据
			return EntityUtils.toString(response.getEntity(), "utf-8");
		} else {
			Logger.error("响应失败，状态码：" + status);
		}
		return null;
	}

}
